import NextAuth, { CredentialsSignin } from "next-auth";
import GitHub from "next-auth/providers/github";
import CredentialsProvider from "next-auth/providers/credentials";
import bcrypt from "bcrypt";
import { authConfig } from "./auth.config";
import { createUser } from "./data";
import { User } from "./models";

const login = async (credentials) => {
  const user = await User.findOne({ username: credentials.username });
  if (!user) {
    // throw new Error("user not found");
    return { reason: "user not found" };
  }
  const isRightPassword = await bcrypt.compare(
    credentials.password,
    user.password
  );
  if (!isRightPassword) {
    return { reason: "password is not correct" };
  }
  return user;
};

export const {
  handlers: { GET, POST },
  signIn,
  signOut,
  auth,
} = NextAuth({
  ...authConfig,
  providers: [
    GitHub({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET,
    }),
    CredentialsProvider({
      async authorize(credentials) {
        // try {
        const user = await login(credentials);
        return user;
        // } catch (error) {
        //   // console.log(error, 88);
        //   throw new Error(error.message);
        //   // return null;
        // }
      },
    }),
  ],
  callbacks: {
    // 登录完拿到信息
    async signIn({ user, account, profile }) {
      // console.log(user, account, profile, 99);
      if (account.provider === "github") {
        const isExistUser = await User.findOne({ email: user.email });
        if (!isExistUser) {
          await createUser({
            email: profile.email,
            username: profile.login,
            img: profile.avatar_url,
          });
        }
      }
      if (account.provider === "credentials") {
        if (user.reason) {
          throw new Error(user.reason);
        }
      }
      return true;
    },
    ...authConfig.callbacks,
    // authorized({ user, request }) {
    //   if (user) {
    //     return true;
    //   }
    //   return false;
    // },
    // async session(session, user) {
    //   return session;
    // },
    // async jwt(token, user, account, profile, isNewUser) {
    //   return token;
    // },
  },
});
